using LitJson;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public enum E_JsonType
{ 
    JsonUtility,
    LitJson
}

public class JsonManager
{
    private static JsonManager instance = new JsonManager();
    public static JsonManager Instance
    {
        get 
        {
            return instance;
        }
    }

    private JsonManager() { }


    public void SaveData(object data, string path, E_JsonType jsonType = E_JsonType.LitJson)
    {
        path = Application.persistentDataPath + '/' + path + ".json";
        Debug.Log(path);

        string jsonData = "";
        if (jsonType == E_JsonType.LitJson)
        {
            jsonData = JsonMapper.ToJson(data);
        }
        else
        { 
            jsonData = JsonUtility.ToJson(data);
        }

        File.WriteAllText(path, jsonData);
    }


    public T LoadData<T>(string s, E_JsonType jsonType = E_JsonType.LitJson) where T : new()
    {
        string path = Application.streamingAssetsPath + '/' + s + ".json";

        if (!File.Exists(path))
        { 
            path = Application.persistentDataPath + '/' + s + ".json";
            if (!File.Exists(path))
            {
                return new T();
            }
        }
        string jsonData = File.ReadAllText(path);

        T obj;

        if (jsonType == E_JsonType.LitJson)
        {
            obj = JsonMapper.ToObject<T>(jsonData);
        }
        else
        { 
            obj = JsonUtility.FromJson<T>(jsonData);
        }

        return obj;
    }
}
